var typeLib = require('../type')
var pathLib = require('path')
var last = require('array-last')


module.exports = arrayLast


function arrayLast (arr, num) {
	if(!Array.isArray(arr)) {
		throw new TypeError('the first argument must be an array')
	}

	if (arr.length === 0) {
		return null;
	}

	// num的默认值为1
	num = typeLib.isNumeric(num) ? +num : 1
	if(num === 1) {
		return arr[arr.length-1]
	}
	var len = arr.length

	// var newLen = num > len ? len : num
	var newLen = num
	var result = new Array(newLen)

	while(newLen) {
		result[--newLen] = arr[--len]
	}

	return result
}





(function() {

console.group()
console.log( last(['a', 'b', 'c', 'd', 'e', 'f']) );

console.log( last(['a', 'b', 'c', 'd', 'e', 'f'], 1) );

console.log( last(['a', 'b', 'c', 'd', 'e', 'f'], 10) );
console.groupEnd()

console.log('\n-----------------------\n')

console.group(pathLib.basename(__filename))
console.log( arrayLastV1(['a', 'b', 'c', 'd', 'e', 'f']) );

console.log( arrayLastV1(['a', 'b', 'c', 'd', 'e', 'f'], 1) );

console.log( arrayLastV1(['a', 'b', 'c', 'd', 'e', 'f'], 10) );
console.groupEnd()


buildTest();

})



function arrayLastV1(arr, num) {
	if(!Array.isArray(arr)) {
		throw new TypeError('the first argument must be an array')
	}

	if (arr.length === 0) {
		return null;
	}

	num = typeLib.isNumeric(num) ? +num : 1
	var len = arr.length
	if(num === 1) {
		return arr[len-1]
	}

	var result = []
	// 从尾部开始遍历
	for (var i = len-1, cnt = 0; cnt < num; i--, cnt++) {
		result.unshift(arr[i])
	}
	return result
}














/**
 * 测试不同版本的函数，返回结果是否一致
 * @return {[type]} [description]
 */
function buildTest() {
	console.log(`\n------   buildTest ${pathLib.basename(__filename)} ... ------\n`)
	
	// console.log(isExitsFunction('arrayLast'))
	// console.log(getTestFunList(arrayLast))
	myTest(arrayLast, ['a', 'b', 'c', 'd', 'e', 'f'], 10);

	/**
	 * 测试不同版本的 函数返回的结果是否一致
	 * @param  {Function}  fn   [description]
	 * @param  {...[type]} args [description]
	 * @return {[type]}         [description]
	 */
	function myTest(fn, ...args) {
		var fnList = getTestFunList(fn)

		var result = []
		for (var i = 0; i < fnList.length; i++) {
			result.push(fnList[i](...args))
		}

		var trasResult = result.map(item => JSON.stringify(item))
		var uniqueTransResult = [... new Set(trasResult)]
		
		// 几组函数的结果 返回值相同
		if(uniqueTransResult.length === 1) {
			return true
		} else {
			console.group('myTest result')
			console.log(result)
			console.groupEnd()
			
			return false 
		}
	}



	/**
	 * 获取多个同一功能，不能实现的函数列表
	 * @param  {Function} fn [description]
	 * @return {[type]}      [description]
	 */
	function getTestFunList(fn) {
		if(typeof fn !== 'function') {
			throw new TypeError('the argument must be an  function ')
		}

		var fnList = [fn]
		var fnMore = null
		var x = 0 
		while(x ++ < 10 ) {
			var isBreak = false ;
			var fnArr = []
			// 不同版本的函数，命名符合一定的规则
			var fnNames = [ fn.name + x , fn.name + `V${x}`, fn.name + `v${x}` ]

			for (var i = 0; i < fnNames.length; i++) {
				fnMore =  isExitsFunction(fnNames[i])
				if(fnMore) {
					fnArr.push(fnMore)
					// fnMore = null
				}
			}

			// 没有找到一个函数
			if(fnArr.length === 0) {
				isBreak = true
			}
			
			fnList = fnList.concat(fnArr)
			if(isBreak) break
		}
		
		return  fnList
	}


	/**
	 * 判断一个函数(字符串)是否存在
	 * @param  {[type]}  funcName        [description]
	 * @param  {Boolean} transToFunction [description]
	 * @return {Boolean}                 [description]
	 */
	function isExitsFunction(funcName, transToFunction = true) {
	  try {
	  	var transFun = eval(funcName)
	    if (typeof(transFun) == "function") {
	      return transToFunction ? transFun : true
	    }
	  } catch(e) {}
	  return false 
	}
}
